/*
 * ConfigurationForm.java
 *
 * Created on 21 2007, 02:41
 * Note: This source code is protected under the This software is licensed under the CC-GNU GPL.
 */
package OpenToday.Configuration;

import OpenToday.IManager;
import javax.microedition.lcdui.Choice;
import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.Spacer;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;


/**
 *
 * @author:  Menny Even Danan (c) 2007. Note: This source code is protected under the This software is licensed under the CC-GNU GPL.
 */
public class ConfigurationForm extends Form implements CommandListener, ItemCommandListener, IFileBrowserCreator {

    private final TextField m_offset;
    private final TextField m_refreshInSeconds;
    private final TextField m_maxEventsToShow;
    private final TextField m_maxDaysToShow;
    private final TextField m_NothingTodayText;
    private final ChoiceGroup m_TextBasedScreen;
    private final TextField m_UTC_events;
    private final TextField m_imagePath;
    private final ChoiceGroup m_UseThemeColors;
    private final TextField m_backgroundColor;
    private final TextField m_dayTextColor;
    private final TextField m_eventTextColor;
    private final TextField m_showOverdueItems;
    private final TextField m_OverdueText;
    private final TextField m_showDoneTasks;
    private final TextField m_showEndTimes;
    private final TextField m_showTodayAlways;
    private final TextField m_discardErrors;
    private final TextField m_titleFontSize;
    private final TextField m_eventsFontSize;

    private final IManager m_manager;

    public ConfigurationForm(IManager manager) {
        super("Configuration");
        super.setTitle("Configuration");

        m_manager = manager;
        //cancel command
        super.addCommand(new Command("Cancel", Command.CANCEL, 0));
        super.setCommandListener(this);
        //save config command
        super.addCommand(new Command("Save", Command.OK, 0));
        super.setCommandListener(this);
        //building form
        OpenTodayConfiguration cnf = OpenTodayConfiguration.getInstance();
        m_offset = AddTextbox("Top offset:", "" + cnf.get_ScreenTopOffset(), true);
        m_refreshInSeconds = AddTextbox("Refresh every (sec):", "" + (cnf.get_RefreshEventsListInMilliseconds() / 1000), true);
        m_maxEventsToShow = AddTextbox("Max events to show:", "" + cnf.get_MaxEventsToShow(), true);
        m_maxDaysToShow = AddTextbox("Days ahead to show:", "" + cnf.get_DaysAheadToLook(), true);
        m_showTodayAlways = AddTextbox("Today always visible:", cnf.getShowTodayAlways());
        m_showDoneTasks = AddTextbox("Show done tasks:", cnf.getShowDoneTasks());
        m_NothingTodayText = AddTextbox("No events text:", cnf.get_NoEventsText(), false);
        m_showOverdueItems = AddTextbox("Show overdue items:", cnf.getShowOverdueItems());
        m_OverdueText = AddTextbox("Overdue items title:", cnf.getOverdueItemsTitle(), false);
        //m_TextBasedScreen = AddTextbox("*Text based screen:", cnf.get_TextBasedTodayScreen());
        m_TextBasedScreen = new ChoiceGroup("*Text based screen:", Choice.EXCLUSIVE, new String[] {"Yes", "No"}, null);
        if (cnf.get_TextBasedTodayScreen()) {
            m_TextBasedScreen.setSelectedIndex(0, true);
        } else {
            m_TextBasedScreen.setSelectedIndex(1, true);
        }
        super.append(m_TextBasedScreen);
        m_UTC_events = AddTextbox("Events stored in UTC:", cnf.get_EventsStoredInUTC());
        m_showEndTimes = AddTextbox("Show end times:", cnf.getShowEndTime());
        m_discardErrors = AddTextbox("Discard errors:", cnf.getDiscardErrors());
        m_titleFontSize = AddTextbox("Title font size (L,M,S):", GetSizeCharFromInt(cnf.getTitleFontSize()), false);
        m_eventsFontSize = AddTextbox("Title font size (L,M,S):", GetSizeCharFromInt(cnf.getEventFontSize()), false);
        m_imagePath = AddTextbox("Background image:", cnf.get_BackgroundImagePath(), false);
        m_imagePath.addCommand(new Command("Browse", Command.ITEM, 1));
        m_imagePath.setItemCommandListener(this);
        m_UseThemeColors = new ChoiceGroup("Use Colors from Theme:", Choice.EXCLUSIVE, new String[] {"Yes", "No"}, null);
        if (cnf.get_UseThemeColors()) {
            m_UseThemeColors.setSelectedIndex(0, true);
        } else {
            m_UseThemeColors.setSelectedIndex(1, true);
        }
        super.append(m_UseThemeColors);

        // display system colors as info
        int bgc = cnf.getSystemBackgroundColor();
        StringItem bgColorInfo = new StringItem("System Background Color: ", Integer.toHexString(bgc));
        super.append(bgColorInfo);
        int fgc = cnf.getSystemForegroundColor();
        StringItem fgColorInfo = new StringItem("System Foreground Color: ", Integer.toHexString(fgc));
        super.append(fgColorInfo);

        m_backgroundColor = AddTextbox("Background color (R,G,B):",
                OpenTodayConfiguration.GetRGBString(cnf.get_BackgroundRGB()),
                false);
        m_dayTextColor = AddTextbox("Day text color (R,G,B):",
                OpenTodayConfiguration.GetRGBString(cnf.get_DayTextRGB()),
                false);
        m_eventTextColor = AddTextbox("Event text color (R,G,B):",
                OpenTodayConfiguration.GetRGBString(cnf.get_EventTextRGB()),
                false);
        AddString("* - Requires application restart.");
    }
//http://cfsearching.blogspot.com/2009/05/java-poi-hwpf-characterproperties.html
    private static Font getFont() {
        return Font.getFont(Font.FACE_PROPORTIONAL, Font.STYLE_PLAIN, Font.SIZE_SMALL);
    }

    private void AddSpacer() {
        super.append(new Spacer(1000, 1));
    }

    private void AddString(String text) {
        StringItem line = new StringItem(null, text);
        line.setFont(getFont());
        line.setLayout(StringItem.LAYOUT_LEFT);
        super.append(line);
    }

    private TextField AddTextbox(String text, String initialValue, boolean numbersOnly) {
        int constraints = numbersOnly ? TextField.NUMERIC + TextField.NON_PREDICTIVE : TextField.ANY;
        TextField textBox = new TextField(text, initialValue, 32, constraints);
        super.append(textBox);
        return textBox;
    }

    private TextField AddTextbox(String text, boolean initialValue) {
        return AddTextbox(text, initialValue ? "Y" : "N", false);
    }

    public void commandAction(Command command, Item item) {
        if (item.equals(m_imagePath)) {
            FileBrowser browser = new FileBrowser(this, m_imagePath.getString());
            m_manager.switchDisplayable(browser);
        }
    }

    public void commandAction(Command command, Displayable displayable) {
        if (command.getCommandType() == Command.CANCEL) {
            System.out.println("ConfigurationForm: CancelPressed");
            // display main GUI
            m_manager.displayYourself();

        } else if (command.getCommandType() == Command.OK) {
            System.out.println("ConfigurationForm: OKPressed");
            OpenTodayConfiguration cnf = OpenTodayConfiguration.getInstance();
            cnf.set_NoEventsText(m_NothingTodayText.getString());
            cnf.set_MaxEventsToShow(Integer.parseInt(m_maxEventsToShow.getString()));
            cnf.set_DaysAheadToLook(Integer.parseInt(m_maxDaysToShow.getString()));
            cnf.set_ScreenTopOffset(Integer.parseInt(m_offset.getString()));
            cnf.set_RefreshEventsListInMilliseconds(Integer.parseInt(m_refreshInSeconds.getString()) * 1000);
            cnf.set_BackgroundImagePath(m_imagePath.getString());
            cnf.set_UseThemeColors(m_UseThemeColors.isSelected(0));

            int[] BK_RGB = OpenTodayConfiguration.GetRGBValues(m_backgroundColor.getString());
            cnf.set_BackgroundRGB(BK_RGB);
            int[] DAY_RGB = OpenTodayConfiguration.GetRGBValues(m_dayTextColor.getString());
            cnf.set_DayTextRGB(DAY_RGB);
            int[] EVENT_RGB = OpenTodayConfiguration.GetRGBValues(m_eventTextColor.getString());
            cnf.set_EventTextRGB(EVENT_RGB);

            //the first value is yes, if this is selected assume text based screen
            cnf.set_TextBasedTodayScreen(m_TextBasedScreen.isSelected(0));

            cnf.set_EventsStoredInUTC(GetBooleanValueFromTextField(m_UTC_events));
            cnf.setDiscardErrors(GetBooleanValueFromTextField(m_discardErrors));
            cnf.setShowOverdueItems(GetBooleanValueFromTextField(m_showOverdueItems));
            cnf.setOverdueItemsTitle(m_OverdueText.getString());
            cnf.setShowDoneTasks(GetBooleanValueFromTextField(m_showDoneTasks));
            cnf.setShowTodayAlways(GetBooleanValueFromTextField(m_showTodayAlways));

            cnf.setTitleFontSize(GetIntFromSizeChar(m_titleFontSize.getString()));
            cnf.setEventFontSize(GetIntFromSizeChar(m_eventsFontSize.getString()));

            cnf.setShowEndTime(GetBooleanValueFromTextField(m_showEndTimes));

            // display main GUI
            m_manager.displayYourself();
        }
    }

    private static boolean GetBooleanValueFromTextField(TextField field) {
        String text = field.getString();
        text.trim();
        if (text.length() == 0) {
            text = "N";
        }
        boolean b = text.equalsIgnoreCase("Y");
        return b;
    }

    public void OnNewImageSelected(String newImage) {
        m_imagePath.setString(newImage);
        // display main GUI
        m_manager.displayYourself();
    }

    public void OnCancel() {
        // display main GUI
        m_manager.displayYourself();
    }

    public void OnError(String error) {
        m_manager.OnError(error);
    }

    private static String GetSizeCharFromInt(int fontSize) {
        if (fontSize == Font.SIZE_LARGE) {
            return "L";
        } else if (fontSize == Font.SIZE_MEDIUM) {
            return "M";
        } else {
            return "S";
        }
    }

    private static int GetIntFromSizeChar(String size) {
        if (size.equalsIgnoreCase("L")) {
            return Font.SIZE_LARGE;
        } else if (size.equalsIgnoreCase("M")) {
            return Font.SIZE_MEDIUM;
        } else {
            return Font.SIZE_SMALL;
        }
    }
}
